import {
    Card,
    Row,
    Col,
    Button,
    Input,
    Select,
    Table,
    Tag,
    Space,
    Skeleton,
    Tooltip,
    Typography,
    message,
    Modal,
    Form,
    Divider,
    Badge,
} from "antd";
import {
    SearchOutlined,
    ReloadOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    TagOutlined,
    BarChartOutlined,
} from "@ant-design/icons";
import { useEffect, useState } from "react";
const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { Item } = Form;
// 1. 新增：推广关键字模拟数据（含关联关系）
const promotionKeywords = [
    {
        id: "KW001",
        keyword: "中医推拿",
        source: "微信推广", // 关联推广来源
        plan: "中医推拿体验啊啊啊啊啊啊", // 关联推广方案
        desc: "适合微信短文案推广，突出“放松肩颈”", // 移动端推广建议
        status: "启用", // 关键字状态：启用/停用
        createTime: "2023-05-20",
        customerCount: 12, // 该关键字带来的客户数（转化效果）
    },
    {
        id: "KW002",
        keyword: "针灸理疗",
        source: "宣传单页",
        plan: "针灸理疗套餐",
        desc: "宣传单页标题用，搭配“缓解疼痛”案例",
        status: "启用",
        createTime: "2023-05-25",
        customerCount: 8,
    },
    {
        id: "KW003",
        keyword: "艾灸养生",
        source: "客户推荐",
        plan: "艾灸养生体验",
        desc: "客户转介绍时用，强调“全家适用”",
        status: "启用",
        createTime: "2023-06-01",
        customerCount: 5,
    },
    {
        id: "KW004",
        keyword: "SPA放松",
        source: "支付宝推广",
        plan: "全身SPA套餐",
        desc: "支付宝Banner用，突出“性价比”",
        status: "停用", // 停用的关键字不参与推广
        createTime: "2023-05-15",
        customerCount: 3,
    },
];
// 原有：客户模拟数据（新增keyword字段，关联关键字）
const customerData = [
    {
        id: "PRO2023001",
        name: "张三",
        phone: "138****8000",
        type: "vip",
        source: "微信推广",
        plan: "中医推拿体验啊啊啊啊啊啊",
        keyword: "中医推拿", // 新增：客户来源关键字
        date: "2023-06-15",
        status: "已完成",
        follower: "李员工",
        nextFollow: "--",
    },
    {
        id: "PRO2023002",
        name: "李四",
        phone: "139****9000",
        type: "clue",
        source: "客户推荐",
        plan: "针灸理疗套餐",
        keyword: "针灸理疗", // 新增：客户来源关键字
        date: "2023-06-12",
        status: "跟进中",
        follower: "王员工",
        nextFollow: "2023-06-20",
    },
    {
        id: "PRO2023003",
        name: "王五",
        phone: "137****7000",
        type: "clue",
        source: "宣传单页",
        plan: "艾灸养生体验",
        keyword: "艾灸养生", // 新增：客户来源关键字
        date: "2023-06-10",
        status: "待跟进",
        follower: "张员工",
        nextFollow: "2023-06-18",
    },
    {
        id: "PRO2023004",
        name: "赵六",
        phone: "135****5000",
        type: "public",
        source: "支付宝推广",
        plan: "全身SPA套餐",
        keyword: "SPA放松", // 新增：客户来源关键字
        date: "2023-06-08",
        status: "已放弃",
        follower: "刘员工",
        nextFollow: "--",
    },
    {
        id: "PRO2023005",
        name: "孙七",
        phone: "136****6000",
        type: "vip",
        source: "微信推广",
        plan: "拔罐理疗体验",
        keyword: "拔罐理疗", // 新增：客户来源关键字
        date: "2023-06-05",
        status: "已完成",
        follower: "李员工",
        nextFollow: "--",
    },
    {
        id: "PRO2023006",
        name: "周八",
        phone: "134****4000",
        type: "clue",
        source: "其他渠道",
        plan: "推拿按摩套餐",
        keyword: "推拿按摩", // 新增：客户来源关键字
        date: "2023-06-03",
        status: "跟进中",
        follower: "王员工",
        nextFollow: "2023-06-19",
    },
    {
        id: "PRO2023007",
        name: "吴九",
        phone: "133****3000",
        type: "public",
        source: "客户推荐",
        plan: "中药熏蒸体验",
        keyword: "中药熏蒸", // 新增：客户来源关键字
        date: "2023-06-01",
        status: "已放弃",
        follower: "张员工",
        nextFollow: "--",
    },
    {
        id: "PRO2023008",
        name: "郑十",
        phone: "132****2000",
        type: "clue",
        source: "宣传单页",
        plan: "刮痧理疗体验",
        keyword: "刮痧理疗", // 新增：客户来源关键字
        date: "2023-05-28",
        status: "待跟进",
        follower: "刘员工",
        nextFollow: "2023-06-17",
    },
];
//推广关键字管理
export const PromotionKeyword = () => {
    const [keywordForm] = Form.useForm();
const [isShowSkeleton, setIsShowSkeleton] = useState(true);
    const [currentKeyword, setCurrentKeyword] = useState(null); // 当前编辑的关键字
    const [keywords, setKeywords] = useState(promotionKeywords);
    const [customers, setCustomers] = useState(customerData);
    // 原有：骨架屏控制
      useEffect(() => {
        const timer = setTimeout(() => {
          setIsShowSkeleton(false);
        }, 2000);
        return () => clearTimeout(timer);
      }, []);
    
    // 新增：关键字管理相关状态
    const [keywordModalVisible, setKeywordModalVisible] = useState(false);
    // 新增：保存关键字（新增/编辑）
    const saveKeyword = async () => {
        try {
            const values = await keywordForm.validateFields();
            if (currentKeyword) {
                // 编辑：更新现有关键字
                const updatedKeywords = keywords.map((item) =>
                    item.id === currentKeyword.id ? { ...item, ...values } : item
                );
                setKeywords(updatedKeywords);
                message.success("关键字编辑成功");
            } else {
                // 新增：生成新关键字（ID+默认值）
                const newKeyword = {
                    id: `KW${String(keywords.length + 1).padStart(3, "0")}`,
                    ...values,
                    createTime: dayjs().format("YYYY-MM-DD"),
                    customerCount: 0, // 初始客户数为0
                };
                setKeywords([...keywords, newKeyword]);
                message.success("关键字新增成功");
            }
            setKeywordModalVisible(false);
            resetKeywordForm();
        } catch (errorInfo) {
            console.log("表单验证失败：", errorInfo);
            message.error("请完善关键字信息");
        }
    };
    // 新增：删除关键字
    const deleteKeyword = (id) => {
        Modal.confirm({
            title: "确认删除",
            content: "删除后该关键字将无法恢复，且关联的客户记录不会受影响",
            okText: "确认",
            cancelText: "取消",
            onOk: () => {
                const filteredKeywords = keywords.filter((item) => item.id !== id);
                setKeywords(filteredKeywords);
                message.success("关键字删除成功");
            },
        });
    };
    // 新增：关键字表格列（移动端适配：隐藏部分列，缩小字体）
    const keywordColumns = [
        {
            title: "关键字ID",
            dataIndex: "id",
            key: "id",
          
            render: (text) => <Text size="small">{text}</Text>,
        },
        {
            title: "推广关键字",
            dataIndex: "keyword",
            key: "keyword",
         
            render: (text) => (
                <Tag color="blue" icon={<TagOutlined />} size="small">
                    {text}
                </Tag>
            ),
        },
        {
            title: "关联来源",
            dataIndex: "source",
            key: "source",
          
            responsive: ["md"], // 仅在中等尺寸以上屏幕显示
            render: (text) => <Text size="small">{text}</Text>,
        },
        // {
        //   title: "关联方案",
        //   dataIndex: "plan",
        //   key: "plan",

        //   responsive: ["md"], // 仅在中等尺寸以上屏幕显示
        //   render: (text) => renderEllipsisText(text, 8),
        // },
        // {
        //   title: "客户数",
        //   dataIndex: "customerCount",
        //   key: "customerCount",

        //   render: (count) => (
        //     <Badge count={count} size="small" color="primary">
        //       <Text size="small">客户</Text>
        //     </Badge>
        //   ),
        // },
        {
            title: "状态",
            dataIndex: "status",
            key: "status",

            render: (status) => renderKeywordStatus(status),
        },
        {
            title: "操作",
            key: "action",
            width: 120,
            fixed: "right",
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="text"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => openKeywordModal(record)}
                        style={{ color: "#1890ff" }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={() => deleteKeyword(record.id)}
                        style={{ color: "#ff4d4f" }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];
    // 新增：渲染关键字状态标签（移动端适配小尺寸）
    const renderKeywordStatus = (status) => {
        return status === "启用" ? (
            <Tag color="success" size="small">启用</Tag>
        ) : (
            <Tag color="gray" size="small">停用</Tag>
        );
    };
    // 新增：获取所有推广来源（用于关键字关联）
    const getSourceOptions = () => {
        const sources = [...new Set(customerData.map((item) => item.source))];
        return [
            { value: "", label: "请选择" },
            ...sources.map((source) => ({ value: source, label: source })),
        ];
    };
    // 新增：重置关键字表单
    const resetKeywordForm = () => {
        keywordForm.resetFields();
        setCurrentKeyword(null);
    };
    // 新增：打开关键字模态框（新增/编辑）
    const openKeywordModal = (keyword = null) => {
        setCurrentKeyword(keyword);
        if (keyword) {
            // 编辑：回显数据
            keywordForm.setFieldsValue({
                keyword: keyword.keyword,
                source: keyword.source,
                plan: keyword.plan,
                desc: keyword.desc,
                status: keyword.status,
            });
        } else {
            // 新增：重置表单
            resetKeywordForm();
        }
        setKeywordModalVisible(true);
    };
    return <>
    {isShowSkeleton?(
          <Skeleton
      paragraph={{ rows: 6 }}
      active
      style={{ width: '100%' }}
    />
    ):(
 <div>
            {/* 关键字操作区 */}
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: 16,
                flexWrap: 'wrap',
                gap: 8
            }}>
                <Title level={2} style={{
                    margin: 0,
                    fontSize: 'clamp(1.5rem, 3vw, 1.875rem)',
                    width: '100%'
                }}>推广关键字管理</Title>
                <Text type="secondary">
                    管理移动端推广关键字，关联来源和方案提升转化
                </Text>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    size="small"
                    onClick={() => openKeywordModal()}
                >
                    新增关键字
                </Button>
            </div>

            {/* 关键字表格 */}
            <Card style={{ width: '100%', boxSizing: 'border-box' }}>
                <Table
                    columns={keywordColumns}
                    dataSource={keywords}
                    rowKey="id"
                    bordered
                    pagination={{
                        pageSize: 6,
                        total: keywords.length,
                        showSizeChanger: false,
                        showTotal: (total) => `共 ${total} 条关键字`,
                        size: "small"
                    }}
                    scroll={{ x: 'max-content', minWidth: 700 }}
                    style={{
                        fontSize: '14px',
                        width: '100%',
                        tableLayout: 'fixed'
                    }}
                />
            </Card>

            {/* 移动端提示 */}
            <div style={{
                marginTop: 16,
                padding: '12px',
                backgroundColor: '#f8fafc',
                borderRadius: 8,
                fontSize: '14px',
                width: '100%',
                boxSizing: 'border-box'
            }}>
                <Text strong style={{ color: '#1890ff' }}>移动端推广建议：</Text>
                <ul style={{ paddingLeft: 20, marginTop: 8 }}>
                    <li style={{ marginBottom: 4 }}>关键字长度控制在4-6字（如“中医推拿”）</li>
                    <li style={{ marginBottom: 4 }}>优先选择“启用”状态的关键字投放</li>
                    <li>查看“客户数”列，优先使用高转化关键字</li>
                </ul>
            </div>

            {/* 5. 推广关键字编辑模态框 */}
            <Modal
                title={currentKeyword ? "编辑推广关键字" : "新增推广关键字"}
                open={keywordModalVisible}
                onCancel={() => setKeywordModalVisible(false)}
                onOk={saveKeyword}
                width="500px"

                style={{ top: 50 }}
                footer={[
                    <Button key="cancel" size="small" onClick={() => setKeywordModalVisible(false)}>
                        取消
                    </Button>,
                    <Button key="save" type="primary" size="small" onClick={saveKeyword}>
                        {currentKeyword ? "保存修改" : "新增"}
                    </Button>
                ]}
            >
                <Form
                    form={keywordForm}
                    layout="vertical"
                    name="keywordForm"
                    style={{ fontSize: '14px', width: '100%' }}
                >
                    {/* 关键字表单内容保持不变 */}
                    <Item
                        name="keyword"
                        label="关键字"
                        rules={[{ required: true, message: '请输入推广关键字' }, { max: 8, message: '关键字长度不超过8字' }]}
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                    >
                        <Input
                            placeholder="请输入4-6字关键字（如“中医推拿”）"
                            size="small"
                        />
                    </Item>
                    <Item
                        name="source"
                        label="关联推广来源"
                        rules={[{ required: true, message: '请选择推广来源' }]}
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                    >
                        <Select
                            placeholder="选择关键字投放的来源"
                            size="small"
                            options={getSourceOptions()}
                        />
                    </Item>

                    <Item
                        name="desc"
                        label="移动端推广建议"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                    >
                        <Input.TextArea
                            rows={3}
                            placeholder="填写适合移动端的推广文案建议"
                            size="small"
                        />
                    </Item>
                    <Item
                        name="status"
                        label="状态"
                        initialValue="启用"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 24 }}
                    >
                        <Select size="small">
                            <Option value="启用">启用（可用于推广）</Option>
                            <Option value="停用">停用（暂不推广）</Option>
                        </Select>
                    </Item>
                </Form>
            </Modal>
        </div>
    )}
       
    </>
}